//
//  PersonViewController.m
//  SoundPill
//
//  Created by 宋旭东 on 15/6/10.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "PersonViewController.h"
#import "playerTableViewController.h"
#import "Player_ShowModel.h"
#import "search_viewController.h"
#import "search_labelController.h"
#import "RecordViewController.h"
#import "userInformationViewController.h"
#import "UIViewController+MMDrawerController.h"
#import "MobClick.h"
#import "Find_ContentView.h"
#import "RankView.h"
#import "JCAlertView.h"
#import "AMPopTip.h"
#import "popTableviewCell.h"
#import "AppDelegate.h"

@interface PersonViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
{
    float offset;
    NSArray *popArray;
    NSString *selectPop;
}

@property (strong, nonatomic) UIButton *musician;
@property (strong, nonatomic) UIButton *content;
@property (strong, nonatomic) UIScrollView *PersonScroll;
@property (nonatomic, strong) AMPopTip *popTip;
@property (strong, nonatomic) UITableView *popTableview;
@property (strong, nonatomic) UIButton *leftBtn;
@property (strong, nonatomic) Find_ContentView *contentView;
@property (strong, nonatomic) RankView *rankView;
@end

@implementation PersonViewController
- (instancetype)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotoPlayer:) name:@"personGoToPlayer" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goToUser:) name:@"gotoUser" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popTipHide:) name:@"personPop" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeRankAttentionInfo:) name:@"rankReload" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(findToRecord:) name:@"findToRecordWithTopic" object:nil];
        popArray =[NSArray arrayWithObjects:@"全部",
                   @"精选",@"参与", nil];

    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
    
    // 设置页面标题
    self.content = [UIButton buttonWithType:UIButtonTypeCustom];
    _content.frame = CGRectMake(0, 0, 60, 30);
    [_content  setTitle:@"话题" forState:UIControlStateNormal];
    [_content setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _content.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [_content addTarget:self action:@selector(content:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_content];
    
    self.musician = [UIButton buttonWithType:UIButtonTypeCustom];
    _musician.frame = CGRectMake(60, 0, 100, 30);
    [_musician  setTitle:@"推荐好友" forState:UIControlStateNormal];
    _musician.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [_musician setTitleColor:[UIColor colorWithWhite:0.405 alpha:1.000] forState:UIControlStateNormal];
    [_musician addTarget:self action:@selector(musician:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_musician];
    
    UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 30)];
    [buttonView addSubview:_content];
    [buttonView addSubview:_musician];
    self.navigationItem.titleView = buttonView;

    UIButton *seaechItem = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [seaechItem setImage:[UIImage imageNamed:@"search@3x"] forState:UIControlStateNormal];
    [seaechItem addTarget:self action:@selector(personSeaechClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:seaechItem];
    self.navigationItem.rightBarButtonItem=rightItem;
    
    self.leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _leftBtn.frame = CGRectMake(0, 0, 30, 30);
    [_leftBtn setBackgroundImage:[UIImage imageNamed:@"find_activity_menu"] forState:UIControlStateNormal];
    [_leftBtn addTarget:self action:@selector(popTipShowHide:) forControlEvents:UIControlEventTouchUpInside];
    _leftBtn.tag = 69;
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:_leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    _leftBtn.hidden = NO;
    
    self.popTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width *0.38, popArray.count * 44) style:UITableViewStylePlain];
    _popTableview.delegate = self;
    _popTableview.dataSource = self;
    _popTableview.backgroundColor = [UIColor blackColor];
    _popTableview.separatorColor = [UIColor clearColor];
    
    self.popTip = [AMPopTip popTip];
    self.popTip.shouldDismissOnTap = YES;
    self.popTip.edgeMargin = 20;
    self.popTip.offset = 2;
    self.popTip.radius = 0;
    self.popTip.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    self.popTip.shouldDismissOnTap = YES;

    [self createContentActivityView];
}
- (void)content:(UIButton *)button
{
    _leftBtn.hidden = NO;
    [_PersonScroll setContentOffset:CGPointZero animated:YES];
    [_content setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [_musician setTitleColor:[UIColor colorWithWhite:0.405 alpha:1.000] forState:UIControlStateNormal];
    _content.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    _musician.titleLabel.font = [UIFont boldSystemFontOfSize:20];
}
- (void)musician:(UIButton *)button
{
    _leftBtn.hidden = YES;
    if ([self.popTip isVisible]) {
        [self.popTip hide];
    }
    [_PersonScroll setContentOffset:CGPointMake(self.view.frame.size.width, 0) animated:YES];
    [_musician setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_content setTitleColor:[UIColor colorWithWhite:0.405 alpha:1.000] forState:UIControlStateNormal];
    _content.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    _musician.titleLabel.font = [UIFont boldSystemFontOfSize:20];
}
- (void)popTipShowHide:(UIButton *)sender
{
    [self popTipHide:nil];
    self.popTip.popoverColor = [UIColor blackColor];
    self.popTip.edgeMargin = sender.center.x;
    self.popTip.arrowSize = CGSizeMake(20, 10);
    [self.popTip showCustomView:_popTableview direction:AMPopTipDirectionDown inView:self.view fromFrame:CGRectMake(sender.center.x, 0, 0, 0)];
}
- (void)popTipHide:(NSNotification *)notification
{
    if ([self.popTip isVisible]) {
        [self.popTip hide];
        return;
    }
}
- (void)personSeaechClick
{
    search_viewController *searchVC = [[search_viewController alloc]init];
    [self.navigationController pushViewController:searchVC animated:YES];
}
- (void)createContentActivityView
{
    self.PersonScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 48)];
    _PersonScroll.contentSize = CGSizeMake(self.view.frame.size.width * 2, 0);
    _PersonScroll.delegate = self;
    _PersonScroll.scrollEnabled = NO;
    _PersonScroll.showsHorizontalScrollIndicator = NO;
    _PersonScroll.pagingEnabled = YES;
    offset = _PersonScroll.contentOffset.x;
    [self.view addSubview:_PersonScroll];
    
    //人物
    self.contentView = [[Find_ContentView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 48) popTip:self.popTip];
    _contentView.ContentTableView.scrollsToTop = YES;
    //    _contentView.backgroundColor = [UIColor redColor];
    [_PersonScroll addSubview:_contentView];

    
    //排行
    self.rankView = [[RankView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 48)];
    //    _activityView.backgroundColor = [UIColor orangeColor];
    [_PersonScroll addSubview:_rankView];
}


- (void)gotoPlayer:(NSNotification *)notification
{
    if ([_popTip isVisible]) {
        [_popTip hide];
        return;
    }
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *isPlay = [userDefaults objectForKey:@"isWiFiPlay"];
    NSString *pppp=[NSString stringWithFormat:@"%u",[self getNetworkTypeFromStatusBar]];
    
    if (([isPlay isEqualToString:@"1"]&&[pppp isEqualToString:@"5"])||[pppp isEqualToString:@"5"]||([isPlay isEqualToString:@"0"]&&![pppp isEqualToString:@"0"])||isPlay==nil){
        NSString *CinemeID = notification.object;
        Player_ShowModel *playModel = [Player_ShowModel sharedInstance];
        UINavigationController *nv = (UINavigationController *)self.mm_drawerController.rightDrawerViewController;
        playerTableViewController *player = (playerTableViewController *)nv.topViewController;
        NSString *showURL = [NSString stringWithFormat:@"http://123.57.1.143/api/work/%@/show", CinemeID];
         AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        NSString *head = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
        [manager.requestSerializer setValue:head forHTTPHeaderField:@"authorization"];
        [manager GET:showURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dic = (NSDictionary *)responseObject;
            NSDictionary *dataDic = [dic valueForKey:@"data"];
            NSDictionary *linksDic = [dic valueForKey:@"links"];
            [playModel setValuesForKeysWithDictionary:dataDic];
            if ([[dic allKeys] containsObject:@"meta"]) {
                NSDictionary *meta = [dic valueForKey:@"meta"];
                NSString *userAvatar = [meta valueForKey:@"userAvatar"];
                player.locUserAvatar = userAvatar;
//                NSArray *array = [meta valueForKey:@"playlist"];
//                player.playList = [NSMutableArray arrayWithArray:array]
//                ;
                playModel.comment_count = [meta valueForKey:@"count"];
                ;
            }
            player.waveform = [linksDic valueForKey:@"waveform"];
            player.workID = CinemeID;
            player.isSelf = NO;
            [player reloadViews:playModel];
            [self.mm_drawerController toggleDrawerSide:MMDrawerSideRight animated:YES completion:^(BOOL finished) {
            }];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    } else {
        [JCAlertView showOneButtonWithTitle:@"你已开启仅Wifi环境播放" Message:@"可以去设置关闭此功能" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
            
        }];
    }
}
-(NETWORK_state)getNetworkTypeFromStatusBar {
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
    NSNumber *dataNetworkItemView = nil;
    for (id subview in subviews) {
        if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]])     {
            dataNetworkItemView = subview;
            break;
        }
    }
    NETWORK_state nettype = NETWORK_state_NONE;
    NSNumber * num = [dataNetworkItemView valueForKey:@"dataNetworkType"];
    nettype = [num intValue];
    return nettype;
}


- (void)changeRankAttentionInfo:(NSNotification *)notification
{
    RankTableViewCell *cell = notification.object;
    NSIndexPath *path = [_rankView.tableView indexPathForCell:cell];
    Rank *musicianInfo = _rankView.rankArray[path.row];
    musicianInfo.follow = @"1";
    [_rankView.rankArray replaceObjectAtIndex:path.row withObject:musicianInfo];
    [_rankView.tableView reloadData];
}
#pragma mark -tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return popArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"pop";
    popTableviewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[popTableviewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor blackColor];
    
    
    if (_PersonScroll.contentOffset.x == 0) {
        cell.content.text = [NSString stringWithFormat:@"%@",popArray[indexPath.row]];
        if ([selectPop isEqualToString:cell.content.text]) {
            cell.selectImage.hidden = NO;
        } else {
            cell.selectImage.hidden = YES;
            if (selectPop == nil && [cell.content.text isEqualToString:@"全部"]) {
                cell.selectImage.hidden = NO;
            }
        }
    } else {
//        cell.content.text = [NSString stringWithFormat:@"%@",popArray[indexPath.row]];
//        
//        if ([labXSelectPop isEqualToString:cell.content.text]) {
//            cell.selectImage.hidden = NO;
//        } else {
//            cell.selectImage.hidden = YES;
//            if (labXSelectPop == nil && [cell.content.text isEqualToString:@"全部"]) {
//                cell.selectImage.hidden = NO;
//            }
//        }
    }
    cell.content.textColor = [UIColor whiteColor];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_PersonScroll.contentOffset.x == 0) {
        self.contentView.type = indexPath.row;
        if (indexPath.row == 1) {
            self.contentView.type = 2;
        } else  if (indexPath.row == 2){
            self.contentView.type = 1;
        }
        selectPop = popArray[indexPath.row];
        [_contentView.contentArray removeAllObjects];
        [_contentView AFNetworking:1 refreshing:nil];
        //        [_contentView.header beginRefreshing];
    } else {
//        labXSelectPop = popArray[indexPath.row];
//        self.activityView.type = indexPath.row;
//        [_activityView.activityArray removeAllObjects];
//        [_activityView AFNetworking:1 refreshing:nil];
    }
    [tableView reloadData];
    if ([self.popTip isVisible]) {
        [self.popTip hide];
    }
}
#pragma mark - 跳转代理
- (void)goToUser:(NSNotification *)notification
{
    if ([_popTip isVisible]) {
        [_popTip hide];
        return;
    }
    NSString *userId = notification.object;
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取字典类型NSDictionary类型的数据
    NSString *uid = [userDefaultes stringForKey:@"uid"];
    if (![userId isEqualToString: uid] ) {
        userInformationViewController *otherSelfVC = [[userInformationViewController alloc]initWithSelfUid:userId];
        [self.navigationController pushViewController:otherSelfVC animated:YES];
    }else if([userId isEqualToString: uid]){
        //自动跳到我的
        if (self.tabBarController.selectedIndex == 4) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        } else {
            [self.tabBarController setSelectedIndex:4];
        }
    }
}
- (void)findToRecord:(NSNotification *)notification
{
    if ([notification.object isKindOfClass:[UILabel class]]) {
        UILabel *la = (UILabel *)notification.object;
        search_labelController *searchLabelVC = [[search_labelController alloc]init];
        [searchLabelVC getTitle:la.text];
        [self.navigationController pushViewController:searchLabelVC animated:YES];
    } else {
        if ([[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] != nil) {
            [AppDelegate shareDelegate].startTag = @"话#题";
            RecordViewController *record = [[RecordViewController alloc] initWithType:[AppDelegate shareDelegate].startTag detile:[AppDelegate shareDelegate].topicString];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:record];
            [self presentViewController:nav animated:YES completion:nil];
        } else {
            [JCAlertView showTwoButtonsWithTitle:@"未登录" Message:@"登录后才能继续操作" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"再看看" Click:^{
                
            } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"去登录" Click:^{
                [[AppDelegate shareDelegate] chooseRootViewController];
            }];
        }
    }
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"人物"];
    [self popTipHide:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
//    [header beginRefreshing];
    [MobClick endLogPageView:@"人物"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.
}
@end
